<?php
/**
 * 配置文件加载
*/

namespace houze;

use event\Run;


class Config extends Run
{
    
    /**
     * 全站配置项
    */
    private static $config = [];

    /**
     * 初始化配置项
    */
    public static function start() {
        $start_time = explode(' ',microtime());

        $path = ROOT_PATH.'/config/';
        $files = scandir($path);
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') continue;
            $key = str_replace('.php', '', $file);
            self::$config[$key] = require $path.$file;
        }

        \houze\StartRecord::config($start_time);
    }

    /**
     * 递归获取多级配置
    */
    private static function loop_get($config, $array) {
        foreach ($array as $k=>$v) {
            if (!isset($array[$k+1])) {
                return $config[$v] ?? false;
            } else {
                unset($array[$k]);
                if (!isset($config[$v])) return false;
                
                return self::loop_get($config[$v], $array);
            }
        }
        return false;
    }

    /**
     * 递归设置多级配置
    */
    private static function loop_set(&$config, $array, $val) {
        if (count($array) == 1 ){
            $config[array_shift($array)] = $val;
        }else{
            //每次弹出一个元素，并且把新的data传递进去
            self::loop_set($config[array_shift($array)], $array, $val);
        }
        return $config;
    }
    /**
     * 获取参数
    */
    public static function get($key=null) {
        if (is_null($key)) {
            return self::$config;
        } else if (strpos($key, '.') !== false) {
            return self::loop_get(self::$config, explode('.', $key));
        } else if (isset(self::$config[$key])) {
            return self::$config[$key];
        }

        return false;
    }

    /**
     * 设置参数
    */
    public static function set($key, $val) {
        $key_arr = explode( '.' , $key);
        $old_config = self::$config;
        self::$config = self::loop_set($old_config, $key_arr , $val);
        unset($old_config);
        return true;
    }

    /**
     * 判断参数是否存在
    */
    public static function has($key) {
        if (strpos($key, '.') !== false) {
            return self::loop_get(self::$config, explode('.', $key));
        } else if (isset(self::$config[$key])) {
            return true;
        }

        return false;
    }
}
